package com.example.demo.Task;


import com.example.demo.domain.send.DingMessage;
import com.example.demo.service.EmptyClassRoomService;
import com.example.demo.service.SendDingMessageService;
import com.example.demo.utils.ParseUtil;
import java.util.Arrays;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.TimerTask;

/**
 * 定时任务爬取空教室信息
 * @author lzq
 */
@Slf4j
@Component
public class GetClassRoomEmptyTimeTask extends TimerTask {

    private static final ThreadPoolTaskExecutor GET_EMPTY_CLASSROOM_POOL = new ThreadPoolTaskExecutor();

    private EmptyClassRoomService emptyClassRoomService;

    static {
        GET_EMPTY_CLASSROOM_POOL.setRejectedExecutionHandler(new CallerRunsPolicy());
        GET_EMPTY_CLASSROOM_POOL.setCorePoolSize(10);
        GET_EMPTY_CLASSROOM_POOL.setMaxPoolSize(10);
        GET_EMPTY_CLASSROOM_POOL.setQueueCapacity(1500);
        GET_EMPTY_CLASSROOM_POOL.setWaitForTasksToCompleteOnShutdown(true);
        GET_EMPTY_CLASSROOM_POOL.initialize();
    }



    @Autowired
    public GetClassRoomEmptyTimeTask(EmptyClassRoomService emptyClassRoomService) {
        this.emptyClassRoomService = emptyClassRoomService;
    }

    @Override
    public void run() {
        try {
            log.info("开始爬取所有空教室信息");
            SendDingMessageService.sendGetDataMessage(new DingMessage("开始爬取所有空教室信息"));
            List<String> allEmptyClassRoom = ParseUtil.getAllEmptyClassRoom();
            log.info("教室总数:"+allEmptyClassRoom.size());
            emptyClassRoomService.deleteEmptyClassRoom();
            for (String classRoom : allEmptyClassRoom) {
                GetClassRoomEmptyTimeThread getClassRoomEmptyTimeThread = new GetClassRoomEmptyTimeThread(
                    emptyClassRoomService, classRoom);
                GET_EMPTY_CLASSROOM_POOL.execute(getClassRoomEmptyTimeThread);
            }
            log.info("所有教室爬取线程已开启");
        }catch (Exception e){
            log.error("getEmptyClassRoom error");
            log.error("errorMessage:"+e.getMessage());
            log.error("stack:"+ Arrays.toString(e.getStackTrace()));
            SendDingMessageService.sendGetDataMessage(new DingMessage("爬取所有空教室失败：errorMessage："+e.getMessage()));
        }
    }
}
